package com.fafi.selfmvc.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WebSocketHander implements WebSocketHandler {
	private static final Log logger = LogFactory.getLog(WebSocketHander.class);

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("afterConnectionEstablished");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		logger.info("handleMessage");
		String params = (String) message.getPayload();
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String,Object> map = mapper.readValue(params, HashMap.class);
		final Object time = map.get("time");
		final Object text = map.get("text");
		final Object clientId = map.get("clientId");
		logger.info(time.toString());
		logger.info(text.toString());
		logger.info(clientId.toString());
		//定时每3秒钟返回给前台数据
		ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(2);
		timer.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {

				TextMessage reply = new TextMessage("time : "+time+"text:"+text+"clientId:"+clientId+"---"+System.currentTimeMillis());
				try {
					session.sendMessage(reply);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}, 0,3 * 1000, TimeUnit.MILLISECONDS);

		session.close();
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		logger.info("handleTransportError");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.info("afterConnectionClosed");
	}

	@Override
	public boolean supportsPartialMessages() {
		logger.info("supportsPartialMessages");
		return false;
	}
}
